<template>
  <div class="create-order">
    <NavBar class="nav-bar">
      <template v-slot:center> 定单预览 </template>
    </NavBar>

    <div class="address-wrap">
      <div class="name" @click="goTo">
        {{ state.address.name }}
        {{ state.address.phone }}
      </div>
      <div class="address">
        {{ state.address.province }} {{ state.address.city }}
        {{ state.address.county }}
        {{ state.address.address }}
      </div>
      <van-icon class="arrow" name="arrow" />
    </div>
    <div class="good">
      <div
        class="good-item"
        v-for="(item, index) in state.cartList"
        :key="index"
      >
        <div class="good-img"><img :src="item.goods.cover_url" alt="" /></div>
        <div class="good-desc">
          <div class="good-title">
            <span>{{ item.goods.title }}</span>
            <span>x{{ item.num }}</span>
          </div>
          <div class="good-btn">
            <div class="price">
              <small>¥</small> {{ item.goods.price + ".00" }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <van-submit-bar
      class="submit-all"
      :price="total * 100"
      button-text="生成订单"
      @submit="handleCreateOrder"
    >
      商品金额
    </van-submit-bar>

    <van-popup
      closeable
      :close-on-click-overlay="false"
      v-model:show="state.showPay"
      position="bottom"
      :style="{ height: '40%' }"
      @close="close"
    >
      <van-grid :border="false" :column-num="2">
        <van-grid-item>
          支付宝二维码<br />
          <van-image width="150" height="150" :src="state.aliyun" />
        </van-grid-item>
        <van-grid-item>
          微信二维码<br />
          <van-image width="150" height="150" :src="state.wechat" />
        </van-grid-item>
      </van-grid>
    </van-popup>
  </div>
</template>

<script>
import { reactive, onMounted, computed } from "vue";
import NavBar from "@/components/common/navbar/NavBar.vue";
import {
  getOrderPreview,
  createOrder,
  payOrder,
  payOrderStatus,
} from "@/network/order";
import {
  Toast,
  SubmitBar,
  Popup,
  Grid,
  GridItem,
  Icon,
  Image as VanImage,
} from "vant";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
export default {
  name: "CreateOrder",
  components: {
    NavBar,
    [Toast.name]: Toast,
    [SubmitBar.name]: SubmitBar,
    [Popup.name]: Popup,
    [Grid.name]: Grid,
    [GridItem.name]: GridItem,
    [Icon.name]: Icon,
    [VanImage.name]: VanImage,
  },
  setup() {
    const router = useRouter();
    const route = useRoute();
    const store = useStore();
    // 每个组件内都会定义的一个 state
    const state = reactive({
      cartList: [],
      address: {},
      // showPay 显示弹出层
      showPay: false,
      // orderNo 订单id
      orderNo: "",
      aliyun: "",
      wechat: "",
    });

    const init = () => {
      Toast.loading({ message: "加载中...", forbidClick: true });
      // 这个API就能直接返回address 和 cart的信息
      getOrderPreview().then((res) => {
        let address = res.data.address.filter((n) => n.is_default == "1");

        if (address.length == 0) {
          state.address = {
            address: "还没有设置默认地址，请选择或填写地址信息",
          };
        } else {
          state.address = address[0];
        }

        state.cartList = res.data.carts;

        Toast.clear();
      });
    };

    onMounted(() => {
      init();
    });

    const goTo = () => {
      router.push({ path: "/address" });
    };
    //处理生成订单
    const handleCreateOrder = () => {
      const params = {
        address_id: state.address.id,
      };

      createOrder(params).then((res) => {
        Toast("创建定单成功");
        // 创建订单后更新购物车数量这里调用updateCart 直接更新购物车数量就好
        // 因为后端已经把删除哪些做好
        store.dispatch("updateCart");

        state.showPay = true;
        // 订单ID
        state.orderNo = res.data.id;
        //获取二维码  ali安卓手机提供了一个沙箱可用来测试
        payOrder(state.orderNo, { type: "aliyun" }).then((res) => {
          // 这里其实wechat 和 aliyun的二维码都是aliyun返回的二维码
          state.aliyun = res.data.qr_code_url;
          state.wechat = res.data.qr_code_url;
        });

        // wechat二维码的获取方法
        /* payOrder(state.orderNo, {type:'wechat'}).then(res=>{
                        state.wechat = res.qr_code_url;
        })*/

        // 轮询查看订单状态 当状态码为2时订单支付成功 跳转到订单详情
        const timer = setInterval(() => {
          payOrderStatus(state.orderNo).then((res) => {
            if (res.data == "2") {
              clearInterval(timer);
              router.push({
                path: "/order-detail",
                query: { id: state.orderNo },
              });
            }
          });
        }, 2000);
      });
    };

    const close = () => {
      router.push({ path: "/order-detail", query: { id: state.orderNo } });
    };
    //计算总价
    const total = computed(() => {
      let sum = 0;
      state.cartList.forEach((item) => {
        sum += parseInt(item.num) * parseFloat(item.goods.price);
      });
      return sum;
    });

    return {
      state,
      goTo,
      handleCreateOrder,
      close,
      total,
    };
  },
};
</script>

<style lang="less" scoped>
.create-order {
  background: #f9f9f9;
  .address-wrap {
    text-align: left;
    margin-bottom: 20px;
    background: #fff;
    position: relative;
    margin-top: 44px;
    font-size: 14px;
    padding: 15px;
    color: #222333;
    .name,
    .address {
      margin: 10px 0;
    }
    .arrow {
      position: absolute;
      right: 10px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 20px;
    }
    &::before {
      position: absolute;
      right: 0;
      bottom: 0;
      left: 0;
      height: 2px;
      background: -webkit-repeating-linear-gradient(
        135deg,
        #ff6c6c 0,
        #ff6c6c 20%,
        transparent 0,
        transparent 25%,
        #1989fa 0,
        #1989fa 45%,
        transparent 0,
        transparent 50%
      );
      background: repeating-linear-gradient(
        -45deg,
        #ff6c6c 0,
        #ff6c6c 20%,
        transparent 0,
        transparent 25%,
        #1989fa 0,
        #1989fa 45%,
        transparent 0,
        transparent 50%
      );
      background-size: 80px;
      content: "";
    }
  }
  .good {
    margin-bottom: 120px;
  }
  .good-item {
    padding: 10px;
    background: #fff;
    display: flex;
    .good-img {
      img {
        width: 100px;
        height: auto;
      }
    }
    .good-desc {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      flex: 1;
      padding: 20px;
      .good-title {
        display: flex;
        justify-content: space-between;
      }
      .good-btn {
        display: flex;
        justify-content: space-between;
        .price {
          font-size: 16px;
          color: red;
          line-height: 28px;
        }
        .van-icon-delete {
          font-size: 20px;
          margin-top: 4px;
        }
      }
    }
  }
  .pay-wrap {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #fff;
    padding: 10px 0;
    padding-bottom: 50px;
    border-top: 1px solid #e9e9e9;
    > div {
      display: flex;
      justify-content: space-between;
      padding: 0 5%;
      margin: 10px 0;
      font-size: 14px;
      span:nth-child(2) {
        color: red;
        font-size: 18px;
      }
    }
    .pay-btn {
      position: fixed;
      bottom: 7px;
      right: 0;
      left: 0;
      width: 90%;
      margin: 0 auto;
    }
  }
}
.submit-all {
  margin-bottom: 50px;
  z-index: 9 !important;
}
</style>
